package com.nxn.core.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nxn.core.dao.EntityDao;
import com.nxn.core.utils.reflection.ReflectionUtils;

/**
 * This class serves as the Base class for all other DAOs - namely to hold
 * common CRUD methods that they might all use. You should only need to extend
 * this class when your require custom CRUD logic.
 * <p/>
 * <p>To register this class in your Spring context file, use the following XML.
 * <pre>
 *      &lt;bean id="fooDao" class="org.nxn.core.dao.hibernate.GenericDaoHibernate"&gt;
 *          &lt;constructor-arg value="org.nxn.core.model.Foo"/&gt;
 *      &lt;/bean&gt;
 * </pre>
 *
 * @author Michael
 * @param <T> a type variable
 * @param <PK> the primary key for that type
 */
public abstract class EntityDaoHibernate<T, PK extends Serializable> 
		extends GenericDaoHibernate<T, PK> implements EntityDao<T, PK> {
    /**
     * Log variable for all child classes. Uses LogFactory.getLog(getClass()) from Commons Logging
     */
    protected final Log log = LogFactory.getLog(getClass());
    private Class<T> entityClass;
    
    /**
     * 通过子类的泛型定义取得对象类型Class.
     * eg.
     * public class UserDao extends EntityDaoHibernate<User, Long>
     */
    @SuppressWarnings("unchecked")
    public EntityDaoHibernate() {
    	entityClass = ReflectionUtils.getSuperClassGenricType(getClass(), 0);
    }
    
    public EntityDaoHibernate(final Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public T get(PK id) {
        return get(entityClass, id);
    }

    public List<T> getAll() {
        return getAll(this.entityClass);
    }
    
    public boolean exists(PK id) {
        return exists(entityClass, id);
    }

    public void remove(PK id) {
       remove(get(id));
    }
    
    public List<T> findByProperty(String propertyName, Object value) {
        return findByProperty(entityClass, propertyName, value);
    }
    
}
